"""
用户路由模块 - 包含钉钉登录功能
"""
from fastapi import APIRouter, HTTPException, Query, Request, Header
from fastapi.responses import RedirectResponse, JSONResponse
from pydantic import BaseModel
from typing import Optional
import urllib.parse
import requests
import json
import datetime

# 导入模型
from models.m import User, Admin, UserRole

# 导入JWT工具
from tool.jwt_utils import create_access_token, create_refresh_token
from tool.jwt_utils import verify_token

# 如需第三方登录，可在此引入对应配置

# 导入权限验证模块
from app.auth.permissions import get_current_user, get_user_roles, get_user_permissions
 
from fastapi import Depends

user_router = APIRouter()

#手机号密码登录
@user_router.get("/login")
async def login(phone: str, password_hash: str):
    user = await User.get_or_none(phone=phone, password_hash=password_hash)
    if not user:
        return {"message": "用户不存在", "status": "error"}

    # 获取用户角色和权限
    user_roles = await get_user_roles(user)
    user_permissions = await get_user_permissions(user)

    access_token_expires = datetime.timedelta(hours=2)
    refresh_token_expires = datetime.timedelta(days=7)

    jwt_access_token = create_access_token(
        data={
            "user_id": user.id,
            "phone": user.phone,
            "nickname": user.nickname
        },
        expires_delta=access_token_expires
    )

    jwt_refresh_token = create_refresh_token(
        data={
            "user_id": user.id,
            "phone": user.phone,
            "nickname": user.nickname
        }
    )

    return {
        "message": "登录成功",
        "status": "ok",
        "data": {
            "user": {
                "id": user.id,
                "phone": user.phone,
                "nickname": user.nickname,
                "avatar_url": user.avatar_url,
                "role": int(user.role),  # 保留原有字段
                "roles": user_roles,  # 新增：角色列表
                "permissions": user_permissions,  # 新增：权限列表
            },
            "access_token": jwt_access_token,
            "refresh_token": jwt_refresh_token,
            "expires_in": 7200  # 2小时，单位秒
        }
    }

@user_router.get("/is_admin")
async def is_admin(authorization: str | None = Header(None)):
    """检查当前用户是否为管理员（需要Bearer Token）"""
    if not authorization or not authorization.lower().startswith("bearer "):
        raise HTTPException(status_code=401, detail="未授权：缺少Bearer Token")

    token = authorization.split(" ", 1)[1].strip()
    payload = verify_token(token)
    if not payload or not payload.get("user_id"):
        raise HTTPException(status_code=401, detail="无效或过期的Token")

    user_id = payload["user_id"]

    # 1) 优先根据用户角色判断
    user = await User.get_or_none(id=user_id)
    if user and int(user.role) == int(UserRole.ADMIN):
        return {"code": 200, "message": "ok", "data": {"is_admin": True}}

    # 2) 兼容存在 Admin 表记录的情况
    admin = await Admin.get_or_none(user_id=user_id, is_active=True)
    return {"code": 200, "message": "ok", "data": {"is_admin": bool(admin)}}



 


class DingTalkUserInfo(BaseModel):
    """钉钉用户信息"""
    unionid: str
    openid: str
    nickname: str
    avatar_url: Optional[str] = None
    mobile: Optional[str] = None


class LoginResponse(BaseModel):
    """登录响应"""
    access_token: str
    refresh_token: str
    expires_in: int
    user_info: dict
"""
第三方登录相关逻辑已移除；仅保留账号密码登录与权限相关接口。
"""


@user_router.post("/refresh-token")
async def refresh_token(refresh_token: str):
    """
    刷新访问令牌
    """
    from tool.jwt_utils import verify_token
    
    # 验证refresh token
    payload = verify_token(refresh_token, token_type="refresh")
    
    if not payload:
        raise HTTPException(status_code=401, detail="无效的刷新令牌")
    
    # 生成新的access token
    new_access_token = create_access_token(
        data={
            "user_id": payload.get("user_id"),
            "phone": payload.get("phone"),
            "nickname": payload.get("nickname")
        }
    )
    
    return {
        "access_token": new_access_token,
        "expires_in": 7200
    }


@user_router.get("/me", summary="获取当前用户信息（包含角色和权限）")
async def get_current_user_info(user: User = Depends(get_current_user)):
    """
    获取当前登录用户的详细信息，包括角色和权限
    前端可以在登录后调用此接口刷新用户权限
    """
    user_roles = await get_user_roles(user)
    user_permissions = await get_user_permissions(user)
    
    return {
        "code": 200,
        "message": "获取成功",
        "data": {
            "user": {
                "id": user.id,
                "phone": user.phone,
                "nickname": user.nickname,
                "avatar_url": user.avatar_url,
                "role": int(user.role),
                "status": int(user.status),
            },
            "roles": user_roles,
            "permissions": user_permissions,
        }
    }


 


# #封面上传
# @user_router.post("/upload")
# async def upload():
#     """
#     上传文件
#     """
#     # 保存文件


